package com.openweixin.sheknows.controller;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.openweixin.sheknows.common.Pager;
import com.openweixin.sheknows.domain.Answer;
import com.openweixin.sheknows.domain.Expert;
import com.openweixin.sheknows.domain.Question;
import com.openweixin.sheknows.domain.User;
import com.openweixin.sheknows.service.AnswerService;
import com.openweixin.sheknows.service.ExpertService;
import com.openweixin.sheknows.service.QuestionService;
import com.openweixin.sheknows.service.UserNewAnswerService;
import com.openweixin.sheknows.service.UserNewScoreService;
import com.openweixin.sheknows.service.UserService;
import com.weichat.util.SimpleUtil;
import com.weichat.weixin.WeixinOpenService;
import com.weichat.weixin.common.WeixinToken;
import com.weichat.weixin.common.WeixinUser;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

	@Autowired
	private UserService service;
	@Autowired
	private ExpertService expService;

	@Autowired
	private AnswerService answerService;
	@Autowired
	private QuestionService questionService;
	@Autowired
	private UserNewScoreService unsService;
	@Autowired
	private UserNewAnswerService unaService;

	@Value("#{settings['wechat.appid']}")
	private String appid;
	@Value("#{settings['wechat.redirect']}")
	private String redirect;
	@Value("#{settings['wechat.secret']}")
	private String secret;



	@RequestMapping("/login")
	public ModelAndView login(@RequestParam("memberType") Short memberType,
			HttpServletResponse resp) {
		ModelAndView mav = new ModelAndView();
		User u = getLoginUser();
		if(getLoginUser()!=null){
			if (USER_MEMBER.equals(memberType)) {
				mav.addObject("hasNewAnswer",unaService.hasNewAnswer(u.getUid()));
				mav.setViewName("member_main");
			} else {
				mav.addObject("hasNewScore",unsService.hasNewScore(u.getUid()));
				mav.setViewName("expert_main");
			}
			return mav;
		}
		WeixinOpenService openService = new WeixinOpenService();
		String params =  "?needUserInfo=false&memberType="+ memberType;
		String uuid = SimpleUtil.nextSimpleString(16);
		try {
			String wexinURI = openService.getOauthAuthorizeUri(appid, redirect+ params, false, uuid);
			resp.sendRedirect(wexinURI);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping("/process-redirect")
	public ModelAndView preccessRedirect(boolean needUserInfo,
			Short memberType, String code, HttpServletResponse resp) {
		ModelAndView mav = new ModelAndView();
		WeixinOpenService openService = new WeixinOpenService();
		try {
			WeixinToken token = openService.getOauthToken(appid, secret, code);
			if (needUserInfo) {
				
				User u = service.get("username", token.getOpenid());
				if (u != null) {
					if (!u.getGroupid().equals(memberType)) {
						mav.addObject("role", memberType);
						mav.setViewName("role_error");
						return mav;
					} else {
						setLoginUserInSession(u);
						if (USER_MEMBER.equals(memberType)) {
							mav.addObject("hasNewAnswer",unaService.hasNewAnswer(u.getUid()));
							mav.setViewName("member_main");
						} else {
							mav.addObject("hasNewScore",unsService.hasNewScore(u.getUid()));
							mav.setViewName("expert_main");
						}
						return mav;
					}
				}
				
				WeixinUser weixinUser = openService.getOauthUser(token.getAccess_token(), token.getOpenid(), "zh_CN");
				mav.addObject("firstBind", true);
				mav.addObject("username", weixinUser.getOpenid());
				mav.addObject("gender", weixinUser.getSex());
				mav.addObject("icon", weixinUser.getHeadimgurl());
				if (USER_MEMBER.equals(memberType)) {
					mav.setViewName("member_main");
				} else {
					mav.setViewName("expert_main");
				}
				//TODO 这里要判断有没有注册，没有的话，插入用户记录完成注册
				return mav;
			} else {
				User u = service.get("username", token.getOpenid());
				if (u != null) {
					if (!u.getGroupid().equals(memberType)) {
						mav.addObject("role", memberType);
						mav.setViewName("role_error");
						return mav;
					} else {
						setLoginUserInSession(u);
						if (USER_MEMBER.equals(memberType)) {
							mav.addObject("hasNewAnswer",unaService.hasNewAnswer(u.getUid()));
							mav.setViewName("member_main");
						} else {
							mav.addObject("hasNewScore",unsService.hasNewScore(u.getUid()));
							mav.setViewName("expert_main");
						}
						return mav;
					}
				} else {
					String uuid = UUID.randomUUID().toString();
					String params = "?needUserInfo=true&memberType="+ memberType;
					String wexinURI = openService.getOauthAuthorizeUri(appid, redirect + params, true, uuid);
					resp.sendRedirect(wexinURI);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping("/save")
	@ResponseBody
	public String save(User bean) {
		String ip = getRequest().getRemoteAddr();
		Timestamp regdate = new Timestamp(System.currentTimeMillis());
		bean.setRegip(ip);
		bean.setRegdate(regdate);
		if (service.get("username", bean.getUsername()) == null) {
			Integer uid = service.save(bean);
			setLoginUserInSession(service.get(uid));
		}

		return SUCCESS;
	}

	private void setLoginUserInSession(User u) {
		setSessionAttribute(SESSION_USER, u);
	}

	@RequestMapping("/edit")
	@ResponseBody
	public ModelAndView edit() {
		User u = getLoginUser();
		ModelAndView mav;
		if (USER_MEMBER.equals(u.getGroupid())) {
			mav = new ModelAndView("member_edit");
			mav.addObject("hasNewAnswer", unaService.hasNewAnswer(u.getUid()));
		} else {
			mav = new ModelAndView("expert_edit");
			mav.addObject("expert", expService.get(u.getUid()));
			mav.addObject("hasNewScore", unsService.hasNewScore(u.getUid()));
		}
		mav.addObject("profile", u);
		return mav;
	}

	@RequestMapping("/update")
	@ResponseBody
	public User update(User bean) {
		service.update(bean);
		bean = service.get(bean.getUid());
		setLoginUserInSession(bean);
		return bean;
	}

	@RequestMapping("/view")
	@ResponseBody
	public ModelAndView view(Integer id) {
		User u = service.get(id);
		ModelAndView mav;
		if (USER_MEMBER.equals(u.getGroupid())) {
			mav = new ModelAndView("member_view");
		} else {
			mav = new ModelAndView("expert_view");
			Expert exp = expService.get(id);
			mav.addObject("expert", exp);
		}
		mav.addObject("profile", u);
		return mav;
	}

	@RequestMapping("/view-answer-list")
	public ModelAndView viewAnswerList(Pager<Question> pager) {
		ModelAndView mav = new ModelAndView("answer_list");
		pager.addNumberParam("uid", getLoginUser().getUid());
		mav.addObject("pager", questionService.findByPager(pager));
		mav.addObject("hasNewAnswer",
				unaService.hasNewAnswer(getLoginUser().getUid()));
		return mav;
	}

	@RequestMapping("/new-score-list")
	public ModelAndView viewScoreList(Pager<Answer> pager) {
		ModelAndView mav = new ModelAndView("score_list");
		pager.addNumberParam("user.uid", getLoginUser().getUid());
		mav.addObject("hasNewScore",
				unsService.hasNewScore(getLoginUser().getUid()));
		mav.addObject("pager", answerService.findByPager(pager));
		return mav;
	}

}
